package com.hd.trans.loader;

import android.os.AsyncTask;

import androidx.fragment.app.FragmentActivity;

import com.hd.trans.db.bean.MediaItem;
import com.hd.trans.files.bean.Album;
import com.hd.trans.files.bean.MediaOptions;

import java.util.ArrayList;
import java.util.List;

/**
 * @author qianjujun
 * @email qianjujun@163.com
 * @createTime 2020/9/27 17:29
 * @describe
 */
public class MediaPresenter {

    private static final String TAG = "MediaPresenter";

    private FragmentActivity context;
    private MediaOptions mediaOptions;
    private MediaCallback callback;


    private Loader loader;

    public void onCreate(FragmentActivity context, MediaCallback callback, MediaOptions options) {
        this.context = context;
        this.mediaOptions = options;
        this.callback = callback;
    }


    private static class Loader extends AsyncTask<MediaLoader,Void,List<MediaItem>>{
        private final MediaCallback callback;

        private Loader(MediaCallback callback) {
            this.callback = callback;
        }



        @Override
        protected List<MediaItem> doInBackground(MediaLoader... mediaLoaders) {
            if(mediaLoaders==null||mediaLoaders.length==0||mediaLoaders[0]==null){
                return new ArrayList<>();
            }
            try {
                return mediaLoaders[0].load();
            }catch (Exception e){
                return new ArrayList<>();
            }
        }

        @Override
        protected void onPostExecute(List<MediaItem> mediaItems) {
            callback.onMediaResult(mediaItems);
        }
    }




    public void onDestroy() {
        cancel();
    }

    private void cancel(){
        if(loader!=null){
            loader.cancel(true);
        }
    }


    public void load(Album album){
        callback.onAlbumLoading();
        cancel();
        loader = new Loader(callback);
        MediaLoader mediaLoader = MediaLoader.getInstance(context,mediaOptions,album);
        if(loader!=null){
            loader.execute(mediaLoader);
        }
    }





    public interface MediaCallback{
        void onMediaResult(List<MediaItem> mediaItemList);

        void onAlbumLoading();
    }
}
